package com.tuanzi.loan.web.bean.family.sms;

import com.base.common.util.RandomUtils;
import com.google.common.collect.Lists;
import com.tuanzi.loan.business.constants.sms.SmsVoiceSendTaskStatus;
import com.tuanzi.loan.business.entity.shortlink.ShortLink;
import com.tuanzi.loan.business.entity.sms.SmsCalculateTask;
import com.tuanzi.loan.business.entity.sms.SmsCalculateTaskStatus;
import com.tuanzi.loan.business.entity.sms.SmsVoiceSendTask;
import com.tuanzi.loan.business.entity.system.Dictionary;
import com.tuanzi.loan.business.service.shortlink.ShortLinkService;
import com.tuanzi.loan.business.service.sms.SmsCalculateTaskService;
import com.tuanzi.loan.business.service.sms.SmsVoiceSendTaskService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.web.configuration.JSFInfoBean;
import com.tuanzi.server.loan_base.constant.sms.LoanSmsLinkType;
import com.tuanzi.server.loan_base.constant.sms.SmsVoicePlatformChannel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import java.util.Date;
import java.util.List;
import java.util.Random;

import static com.tuanzi.loan.business.constants.DictionaryCode.*;

/**
 * @Author: chenweijun
 * @Date: 2018/10/22 11:29
 * @Description:
 */
@Data
@Slf4j
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class SendVoiceSmsBean extends JSFInfoBean<SmsVoiceSendTask> {

    @Autowired
    private SmsCalculateTaskService smsCalculateTaskService;
    @Autowired
    SmsVoiceSendTaskService smsVoiceSendTaskService;
    @Autowired
    private ShortLinkService shortLinkService;


    @Value("${shortLink-host}")
    private String shortLinkHost;

    private Integer selectedTemplateGroup;
    private List<Dictionary> smsTemplates;
    private String activityName;
    private ShortLink shortLinkEntity = new ShortLink();
    private String shortLink;

    @PostConstruct
    private void init() {
        String id = getParamFromRequest("id");

        if (StringUtils.isBlank(id)) {
            forceRedirect("/views/family/user-info/send-sms/calculate-sms.xhtml");
            return;
        }

        SmsCalculateTask smsCalculateTask = smsCalculateTaskService.findOne(NumberUtils.toLong(id));

        if (smsCalculateTask == null) {
            forceRedirect("/views/family/user-info/send-sms/calculate-sms.xhtml");
            return;
        }
        $ = smsVoiceSendTaskService.addSmsVoiceSendTask(smsCalculateTask.getId());
    }

    @Override
    protected List<String> getDictionaryCodes() {
        return Lists.newArrayList(PLATFORM, SMS_VOICE_PLATFORM_CHANNEL, SMS_VOICE_ID );
    }

    public void onSend() {

        if ($.getPlatformChannel() == null) {
            addErrorMessage("请选择短信平台渠道");
            return;
        }


        if($.getExecuteTime() != null && $.getExecuteTime().before(new Date())){
            addErrorMessage("计划发送时间不能早于当前时间");
            return;
        }

        if(StringUtils.isBlank($.getFirstPartyName())) {
            addErrorMessage("请输入甲方名称");
            return;
        }

        if(StringUtils.isBlank($.getVoiceId())){
            addErrorMessage("请选择语音模板");
            return;
        }

        //校验语音模板跟语音通道是否对应
        String voiceName = translate(SMS_VOICE_ID, $.getVoiceId());
        if($.getPlatformChannel().equals(SmsVoicePlatformChannel.OUYI.getId()) && !voiceName.startsWith("欧一")){
            addErrorMessage("请选择欧一通道的语音模板");
            return;
        }
        if($.getPlatformChannel().equals(SmsVoicePlatformChannel.KEFAN.getId()) && !voiceName.startsWith("科帆")){
            addErrorMessage("请选择科帆通道的语音模板");
            return;
        }




        if ($.getExecuteTime() == null) {
            $.setExecuteTime(new Date());
        }

        SmsCalculateTask smsCalculateTask = smsCalculateTaskService.findOne($.getCalculateTaskId());
        $.setStatus(SmsVoiceSendTaskStatus.READY_SEND);
        if (smsCalculateTask.getStatus() != SmsCalculateTaskStatus.CALCULATE_DONE) {
            $.setStatus(SmsVoiceSendTaskStatus.WAITING_CALCULATE_DONE);
        }

        smsCalculateTask.setSentCount(smsCalculateTask.getSentCount() + 1);
        smsVoiceSendTaskService.saveOrUpdate($);
        smsCalculateTaskService.saveOrUpdate(smsCalculateTask);
        addInfoMessage("操作成功,任务已加入发送队列");
    }

    @Transactional
    public void onTransferLink(Long smsSendTaskId) {

        if($.getLinkType() == null) {
            addErrorMessage("请选择短信链接类型");
            return;
        }

        if(shortLinkEntity.getEnvironment() == null){
            addErrorMessage("请选择作用环境");
            return;
        }

        if (StringUtils.isBlank(shortLinkEntity.getUrl())) {
            addErrorMessage("请输入短信链接");
            return;
        }

        if (StringUtils.isBlank(shortLinkEntity.getActivity())) {
            addErrorMessage("请输入项目");
            return;
        }

        if (StringUtils.isBlank(shortLinkEntity.getMemo())) {
            addErrorMessage("请输入备注");
            return;
        }

        String url = shortLinkEntity.getUrl();
        if($.getLinkType() == LoanSmsLinkType.LOAN_LINK) { //如果是菠萝贷链接，链接拼上短信任务ID参数，追踪埋点数据
            if (!url.contains("sms_task_id")) {
                if (url.contains("?")) {
                    url = url + "&sms_task_id=" + smsSendTaskId;
                } else {
                    url = url + "?sms_task_id=" + smsSendTaskId;
                }
            }
        }

        String slink = RandomUtils.getRandomMixString(new Random().nextInt(2) + 4);
        shortLinkEntity.setUrl(url);
        shortLinkEntity.setShortLink(slink);
        shortLinkEntity.setCtime(new Date());
        shortLinkService.saveOrUpdate(shortLinkEntity);

        shortLink = shortLinkHost + shortLinkEntity.getShortLink();

        //短信任务保存短链接
        $.setShortLink(shortLinkEntity.getShortLink());
        smsVoiceSendTaskService.saveOrUpdate($);
    }

}
